package demo.security;

import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

@Configuration
@EnableOAuth2Sso
//@EnableWebSecurity
public class SsoConfiguration extends WebSecurityConfigurerAdapter {

    /*
     * https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html#_client_token_relay 
     * 
     * OAuth2RestTemplate created from OAuth2ClientContext in request scope and an autowired OAuth2ProtectedResourceDetails,
     * and then the context will always forward the access token downstream, also refreshing the access token automatically if it expires. 
     * 
     * https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html#_client_token_relay_in_zuul_proxy
     * 
     */
	@Bean("MyOAuth2RestTemplate")
    public OAuth2RestTemplate OAuth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
    	return new OAuth2RestTemplate(resource, context);
    }    
	
    @Override
    public void configure(HttpSecurity http) throws Exception {
    	
    	 // @formatter:off
	      http
	          .logout().logoutSuccessUrl("/").and()
	          .authorizeRequests()
	          		.antMatchers("/index.html","/").permitAll()
	          		.anyRequest().authenticated()
	          		.and()
	          .csrf()
	            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
	      // @formatter:on
    }
}
